<template>
  <view class="chat-container">
    <scroll-view 
      class="message-list" 
	  :style="{height: `calc(100vh - ${height}px)`}"
      scroll-y 
	  :scroll-top="scrollTop"
      scroll-with-animation
	  @scroll="userScroll"
	  @scrolltolower="scrolltolower"
    >
      <view 
        v-for="(msg, index) in messages" 
        :key="index"
        :id="`msg-${index}`"
        :class="['message-item', `role-${msg.role}`]"
      >
        <view class="avatar">
			<image class="image" v-if="msg.role === 'user'" :src="userInfo.headImg"></image>
			<image class="image" v-if="msg.role === 'assistant'" src="https://lf-coze-web-cdn.coze.cn/obj/eden-cn/lm-lgvj/ljhwZthlaukjlkulzlp/coze/chatsdk-logo.png"></image>
        </view>
		
		<view class="right-user" v-if="msg.role === 'user'">
			<view class="user-name">
				{{userInfo.nickname}}
			</view>
			<view class="content" ><ua-markdown :source="msg.content" /></view>
			<view class="time">{{ formatTime(msg.timestamp) }}</view>
		</view>
		<view style="flex: 1;" v-if="msg.role === 'assistant'">
			<view class="assistant-name">
				医护流程图
			</view>
			<view class="content">
				<ua-markdown :source="msg.content" />
			</view>
			<view class="time">{{ formatTime(msg.timestamp) }}</view>
		</view>
		
        <!-- <view class="time">{{ formatTime(msg.timestamp) }}</view> -->
      </view>
      <view v-if="isLoading" class="loading"><up-loading-icon textSize="18"></up-loading-icon></view>
      <view v-if="error" class="error">{{ error }}</view>
	  
	  <view id="bottom" style="height: 100rpx;"></view>
    </scroll-view>
    
    <view class="input-area">
      <textarea 
        v-model="inputContent" 
        placeholder="请输入消息..."
        @confirm="handleSend"
		auto-height
		:maxlength="100000"
      ></textarea>
      <button 
        @click="handleSend" 
        :disabled="!inputContent.trim() || isLoading"
      >
        发送
      </button>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted, watch, getCurrentInstance, nextTick } from 'vue';
import { useChat } from '@/uilts/composables/useCoze';
import {onLoad, onShow} from "@dcloudio/uni-app";

// 智能体配置
const BOT_ID = '7522744593398841363'; // 替换为实际Bot ID

// 输入内容
const inputContent = ref('');

// 使用对话组合式函数
const {
  messages,
  isLoading,
  error,
  sendMessage,
  streamMessage,
  clearMessages
} = useChat(BOT_ID);

const _this = getCurrentInstance().proxy;


const userInfo = uni.getStorageSync('userInfo')
const height = ref(0)

const scrollTop = ref(0)
// 是否自动滚动
const isAutomaticRoll = ref(true);

const bottomTop = ref(0)

onShow(() => {
	nextTick(() => {
		const query = uni.createSelectorQuery().in(_this);
		query.select('.input-area').boundingClientRect();
		query.exec((res) => {
			// console.log(".input-area" , res)
			height.value = res[0].height;
		});
	})
})

watch(() => messages.value[messages.value.length-1]?.content, ()=>{
	console.log("执行了", isAutomaticRoll.value)
	nextTick(() => {
		const query = uni.createSelectorQuery().in(_this);
		query.select('#' + `msg-${messages.value.length - 1}`).boundingClientRect();
		query.exec((res) => {
			// console.log("res", res[0].bottom)
			if (res[0]) if (isAutomaticRoll.value) scrollTop.value = res[0].bottom;
		});
		
		
		query.select('#bottom').boundingClientRect();
		query.exec((res) => {
			console.log("#bottom" , res)
			bottomTop.value = res[1].top;
		});
	})
	 
	// lastMessageId.value = `msg-${messages.value.length - 1}`
})

const userScroll = (e) => {
	console.log("userScroll", e)
	isAutomaticRoll.value = false;
}
// 最后一条消息ID（用于自动滚动）
// const lastMessageId = computed(() => {
//   return messages.value.length ? `msg-${messages.value.length - 1}` : '';
// });

// 组件挂载时添加欢迎消息
onMounted(() => {
	console.log("zhixinle")
  // 检查是否有历史消息，无消息时添加欢迎语
  if (messages.value.length === 0) {
    messages.value.push({
      role: 'assistant',
      content: '嗨，你好！我可以为你提供很多宝贵知识哦。',
      timestamp: new Date().toISOString()
    });
  }
});

// 发送消息处理
const handleSend = async () => {
  const content = inputContent.value.trim();
  if (!content) return;
  
  try {
	  // nextTick(() => {
	  // 	const query = uni.createSelectorQuery().in(_this);
	  // 	query.select('#bottom').boundingClientRect();
	  // 	query.exec((res) => {
	  // 		console.log("#bottom" , res)
	  // 		scrollTop.value = res[0].top;
			// isAutomaticRoll.value = true;
	  // 	});
	  // })
	  
    // 普通对话
    // await sendMessage(content);
    isAutomaticRoll.value = true;
	scrollTop.value = bottomTop.value;
    // 流式对话（推荐）
    await streamMessage(content);
    // lastMessageId.value = `msg-${messages.value.length - 1}`
    inputContent.value = '';
  } catch (err) {
    // 错误已在useChat中处理
  }
};
const scrolltolower = () => {
	console.log("到底了")
	// isAutomaticRoll.value = true;
	// scrollTop.value = bottomTop.value;
}
// 格式化时间
const formatTime = (timestamp) => {
  const date = new Date(timestamp);
  return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
};
</script>

<style  lang="scss" scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  padding: 16rpx;
  box-sizing: border-box;
}

.message-list {
	height: 500rpx;
  // flex: 1;
  // margin-bottom: 16rpx;
}

.message-item {
  display: flex;
  margin-bottom: 20rpx;
}

.role-user {
  flex-direction: row-reverse;
}

.avatar {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  background: #eee;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16rpx;
  font-size: 28rpx;
}

.image {
  width: 100%;
  height: 100%;
}

.role-user .avatar {
  margin-right: 0;
  margin-left: 16rpx;
}

.content {
  max-width: 60%;
  padding: 16rpx;
  border-radius: 16rpx;
  font-size: 32rpx;
  background: rgba(150,159,255, 0.45);
  line-height: 1.5;
}

.role-user .content {
max-width: 60%;
padding: 16rpx;
border-radius: 16rpx;
font-size: 32rpx;
  background: #007aff;
  color: white;
}

.time {
  font-size: 24rpx;
  color: #999;
  margin-top: 8rpx;
  // margin-left: 16rpx;
}

.role-user .time {
  margin-left: 0;
  // margin-right: 16rpx;
  text-align: right;
}

.input-area {
	display: flex;
    position: fixed;
    right: 0;
    left: 16rpx;
    bottom: 0;
    gap: 16rpx;
    background: #FFF;
    // height: 100rpx;
    padding-right: 16rpx;
    padding-top: 20rpx;
	padding-bottom: 20rpx;
}

textarea {
  flex: 1;
  max-height: 200rpx;
  border: 1px solid #ddd;
  border-radius: 8rpx;
  padding: 16rpx;
  font-size: 32rpx;
  border-radius: 100rpx;
}

button {
  width: 140rpx;
  height: 72rpx;
  line-height: 72rpx;
  background: #007aff;
  color: white;
  border: none;
  border-radius: 8rpx;
  font-size: 28rpx;
}

button:disabled {
  background: #ccc;
}

.loading {
  text-align: center;
  color: #666;
  padding: 16rpx;
}

.error {
  text-align: center;
  color: #ff3300;
  padding: 16rpx;
}

@mixin name {
	font-size: 24rpx;
	font-weight: 400;
	color: rgba(32,41,69,.62);
	line-height: 24rpx;
	padding-bottom: 12rpx;
}
.user-name {
	@include name;
	text-align: right;
	max-width: 60%;
}

.assistant-name {
	@include name;
	text-align: left;
	max-width: 60%;
}
.right-user {
	display: flex;
	flex-direction: column;
	justify-content: flex-end;
	align-items: flex-end;
	flex: 1;
}
</style>